package com.fq.ability.shiro;
import com.alibaba.fastjson.JSONObject;
import com.fq.ability.redis.constant.RedisConstant;
import com.fq.ability.redis.service.RedisService;
import com.fq.ability.shiro.jwt.JwtToken;
import com.fq.ability.shiro.jwt.JwtUtils;
import com.fq.api.api.ApiError;
import com.fq.modules.sys.role.entity.SysRole;
import com.fq.modules.sys.role.enums.RoleType;
import com.fq.modules.sys.role.service.SysUserRoleService;
import com.fq.modules.sys.user.dto.SysUserLoginDTO;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @Author 超chao
 * @Description 用户登录鉴权和获取用户授权
 * @Date 2024/10/12/周六 15:07
 * @Version 1.0
 */
@Component
@Log4j2
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private RedisService redisService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }


    /**
     * 获取授权信息
     *
     * @param principals 主体集合，包含用户身份信息
     * @return AuthorizationInfo 授权信息，包含用户角色和权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 初始化用户ID
        Long userId = null;
        // 如果主体集合不为空，获取用户ID
        if (principals != null) {
            SysUserLoginDTO user = (SysUserLoginDTO) principals.getPrimaryPrincipal();
            userId = user.getId();

        }
        // 创建授权信息对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 查找用户角色
        SysRole sysRole = sysUserRoleService.userRole(userId);
        List<String> userRoles = new ArrayList<>();
        String roleId = sysRole.getId();
        userRoles.add(roleId);
        info.setRoles(new HashSet<>(userRoles));

        if (roleId.equals(RoleType.ROLE_SUPER_ADMIN.getType())){
            info.addStringPermissions(List.of("*"));
        } else {
            // 查找权限明细
            List<String> permissions = sysUserRoleService.findUserPermission(userId);
            info.addStringPermissions(permissions);
        }


        return info;
    }

    /**
     * 校验用户的账号密码是否正确
     *
     * @param auth
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) {
        String token = (String) auth.getCredentials();
        if (token == null) {
            throw new AuthenticationException(ApiError.ERROR_10020001.msg);
        }
        // 校验token有效性
        SysUserLoginDTO user = this.checkToken(token);

        return new SimpleAuthenticationInfo(user, token, getName());
    }


    /**
     * 校验Token的有效性
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    public SysUserLoginDTO checkToken(String token) {
        Long userId = null;
        try {
            userId = JwtUtils.getUsername(token);
            if (userId == null) {
                throw new AuthenticationException(ApiError.ERROR_10020001.msg);
            }
        } catch (Exception e) {
            throw new AuthenticationException(ApiError.ERROR_10020001.msg);
        }
        // 校验token
        if (!JwtUtils.verify(token, userId)){
            throw new AuthenticationException(ApiError.ERROR_10020001.msg);
        }

        // 查找登录用户对象
        JSONObject json = redisService.getJson(RedisConstant.USER_NAME_KEY + userId);
        if (json == null) {
            // 判 null 解决数据 shiro 异常报错
            throw new AuthenticationException(ApiError.ERROR_10020001.msg);
        }
        SysUserLoginDTO user = json.toJavaObject(SysUserLoginDTO.class);

        if (JwtUtils.KICK_OUT){
            if (!token.equals(user.getToken())){
                throw new AuthenticationException(ApiError.ERROR_10020024.msg);
            }
        }

        return user;
    }

    /**
     * 清除当前用户的权限认证缓存
     *
     * @param principals
     */
    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }


}
